<template>
  <div class="user-info-container">
    <div class="user-avatar-container">
      <img 
        v-if="userInfo.img" 
        :src="userInfo.img" 
        alt="用户头像" 
        class="user-avatar" 
      />
    </div>
    <p class="user-info-title">用户信息</p>
    <ul class="user-info-list">
      <li>用户名：{{ userInfo.username }}</li>
      <li>角色: {{ userInfo.role }}</li>
      <li>邮箱: {{ userInfo.email }}</li>

   
    </ul>
    <div class="button-group">
      <el-button type="primary" @click="openEditWin">修改信息</el-button>
      <el-button type="primary" @click="openChangePasswordWin">修改密码</el-button>
    </div>
  </div>

  <!-- 编辑信息弹出框 -->
  <el-dialog v-model="editWinVisible" title="修改用户信息" width="500">
    <el-form :model="editObject">
      <el-form-item label="头像" label-width="80">
        <el-upload
          class="avatar-uploader"
          action="/api/userimg"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
         
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="用户名" label-width="80">
        <el-input v-model="editObject.username" autocomplete="off"  disabled />
      </el-form-item>
      <el-form-item label="角色" label-width="80">
        <el-select v-model="editObject.role" placeholder="请选择角色">
          <el-option label="管理员" value="管理员" />
          <el-option label="用户" value="用户" />
        </el-select>
      </el-form-item>
      <el-form-item label="邮箱" label-width="80">
        <el-input v-model="editObject.email" autocomplete="off" />
      </el-form-item>
      
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="editWinVisible = false">取消</el-button>
        <el-button type="primary" @click="editSave">保存</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 修改密码弹出框 -->
  <el-dialog v-model="changePasswordWinVisible" title="修改密码" width="300">
    <el-form :model="changePasswordObject">
      <el-form-item label="原密码" label-width="80">
        <el-input v-model="changePasswordObject.originalPassword" :type="showPassword ? 'text' : 'password'" autocomplete="off" />
      </el-form-item>
      <el-form-item label="新密码" label-width="80">
        <el-input v-model="changePasswordObject.newPassword" :type="showPassword ? 'text' : 'password'" autocomplete="off" />
      </el-form-item>
      <el-form-item label="确认密码" label-width="80">
        <el-input v-model="changePasswordObject.confirmNewPassword" :type="showPassword ? 'text' : 'password'" autocomplete="off" />
      </el-form-item>
      <el-form-item>
        <el-checkbox v-model="showPassword">显示密码</el-checkbox>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="changePasswordWinVisible = false">取消</el-button>
        <el-button type="primary" @click="changePasswordSave">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import * as auth from '../util/auth'; // 导入 auth.js
import hospitalapi from '../api';
import { ElMessage } from 'element-plus'; // 导入 ElMessage
import { useRouter } from 'vue-router'; // 导入 useRouter
import { sortOrders } from 'element-plus/es/components/table-v2/src/constants';

const router = useRouter(); // 获取路由实例

const username = ref('');
const userInfo = ref({});
const editWinVisible = ref(false);
const editObject = ref({});
const imageUrl = ref(''); // 用于存储头像 URL
const changePasswordWinVisible = ref(false);
const changePasswordObject = ref({
  originalPassword: '',
  newPassword: '',
  confirmNewPassword: '',
});
const showPassword = ref(false); // 添加显示密码状态

onMounted(async () => {
  const savedUserInfo = auth.getUserInfo();
  if (savedUserInfo) {
    username.value = savedUserInfo.username;
    try {
      // 使用 API.get 发送 GET 请求获取用户信息
      console.log(savedUserInfo)
      let result = await hospitalapi.get("/api/username", savedUserInfo);
      
      if (result.data ) {
        userInfo.value = result.data[0]; // 获取用户数据

        // 将 API 响应中的 img 属性赋值给 userInfo.img
        if (result.data[0].img) {
          userInfo.value.img ="api/img/" +result.data[0].img;
          imageUrl.value = result.data[0].img; // 初始化 imageUrl
        
          
        }
      } else {
        console.error('未找到用户');
      }
    } catch (error) {
      console.error('获取用户信息失败:', error);
    }
  }
});

const openEditWin = () => {
  console.log(imageUrl.value) 
  console.log(userInfo.value)
  editObject.value = { ...userInfo.value }; // 复制用户信息到 editObject
  editWinVisible.value = true; 
};

const editSave = async () => {
  try {
    // 使用 API.put 发送 PUT 请求更新用户信息
    
    console.log(editObject.value) 
    let result = await hospitalapi.putJson('/api/user', editObject.value);
    if (result.code === 200) {
      // 更新 userInfo
      userInfo.value = { ...editObject.value };
      ElMessage({
        type: 'success',
        message: '更新成功',
      });
      editWinVisible.value = false;

      // 获取更新后的图片 URL
      let result = await hospitalapi.get("/api/userimg", editObject.value); // 这里可能需要修改 API 路径
      if (result.data.img != null) {
        console.log(result.data.img);
        imageUrl.value = result.data.img;
      } else {
        imageUrl.value = null;
      }
    } else {
      ElMessage({
        type: 'error',
        message: '更新失败',
      });
    }
  } catch (error) {
    console.error('更新用户信息失败:', error);
  }
};

const openChangePasswordWin = () => {
  changePasswordWinVisible.value = true;
  changePasswordObject.value.originalPassword = ''; // 清空原密码
  changePasswordObject.value.newPassword = ''; // 清空新密码
  changePasswordObject.value.confirmNewPassword = ''; // 清空确认密码
  showPassword.value = false; // 初始化显示密码状态
};

const changePasswordSave = async () => {
  let hasError = false; // 用于标记是否有错误
  let errorMessage = ''; // 用于存储错误信息

  // 验证原密码
  let result = await hospitalapi.get(`/api/password?username=${username.value}&password=${changePasswordObject.value.originalPassword}`);
  if (result.code !== 200) {
    hasError = true;
    errorMessage = '原密码错误';
  }

  // 验证新密码和确认密码是否一致
  if (changePasswordObject.value.newPassword !== changePasswordObject.value.confirmNewPassword) {
    hasError = true;
    errorMessage = '两次输入的密码不一致';
  }

  if (hasError) {
    ElMessage.error(errorMessage);
    return;
  }

  try {
    // 使用 API.put 发送 PUT 请求修改密码
    result = await hospitalapi.putJson(`/api/updatePassword?username=${username.value}&password=${changePasswordObject.value.newPassword}`);
    if (result.code === 200) {
      ElMessage.success('密码修改成功');
      changePasswordWinVisible.value = false;

      // 退出登录并清空 token
      auth.clearToken();
      router.push('/login'); // 跳转到登录页面
    } else {
      ElMessage.error('密码修改失败');
    }
  } catch (error) {
    console.error('修改密码失败:', error);
    ElMessage.error('修改密码失败');
  }
};

const handleAvatarSuccess=function(result,uploadFile){
  imageUrl.value="api"+result.data;
  console.log(imageUrl.value +"===")
  editObject.value.img=imageUrl.value;
}



</script>

<style scoped>
.user-info-container {
  display: flex;
  flex-direction: column;
  align-items: center; /* 居中 */
  width: 500px; /* 调整宽度 */
  padding: 20px;
  height: 388px;
  border: 1px solid #ccc;
  border-radius: 5px;
  box-shadow: 0 2px 5px rgba(58, 3, 68, 0.1);
}

.user-name {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 10px;
}

.user-info-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
}

.user-info-list {
  list-style: none;
  padding: 0;
}

.user-info-list li {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
}

.user-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin-bottom: 10px; /* 添加头像底部间距 */
}

.user-avatar-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 20px; /* 添加头像底部间距 */
}

.avatar-uploader {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  border: 1px dashed #ccc;
  cursor: pointer;
  margin-bottom: 10px;
}

.avatar-uploader-icon {
  font-size: 24px;
  color: #ccc;
}

.avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
}

.button-group {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}
</style>